package com.mysen.sso.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.mysen.model.Response;
import com.mysen.sso.model.User;
import com.mysen.sso.service.UserService;

@RequestMapping("/register")
@Controller
public class RegisterController {

	private static final Logger LOGGER = LoggerFactory.getLogger(RegisterController.class);
	
	@Reference
	private UserService service;
	
	@PostMapping
	@ResponseBody
	public Response<User> register(@RequestBody User user){
		LOGGER.info("user : {} register...", user.getUsername());
		Response<User> resp = new Response<>();
		try {
			if(!service.existsUserByName(user.getUsername())) {
				service.save(user);
				resp.setSuccess(true);
				resp.setData(user);
			} else {
				resp.setErrorMsg("Username is exist!");
				resp.setSuccess(false);
			}
		}catch (Exception e) {
			LOGGER.error("register user error!", e);
			resp.setErrorMsg("unkown error!");
			resp.setSuccess(false);
		}
		return resp;
	}
	
}
